package com.outsider.util;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outsider.news.dao.PhoenixNews;

public class PhoenixNewsUtil {
	private static final String LATEST_NEWS_URL="http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10,SYRECOMMEND&page=1";
	
	public static void updateLatestNews(){
		OkHttp3 okHttp3=OkHttp3.getInstance();
		PhoenixNews.dao.deleteAll();
		String json=okHttp3.get(LATEST_NEWS_URL);
		JSONObject body=JSONObject.parseArray(json).getJSONObject(0);
		JSONArray item=body.getJSONArray("item");
		if (item!=null){
			for (int i=0;i<item.size();i++){
				JSONObject news=item.getJSONObject(i);
				if ("doc".equals(news.getString("type"))){
					PhoenixNews phoenixNews=new PhoenixNews();
					phoenixNews.setTitle(news.getString("title"));
					phoenixNews.setImage(news.getString("thumbnail"));
					phoenixNews.setUrl(news.getString("commentsUrl"));
					phoenixNews.save();
				}
			}
			Logger.getLogger("").info("Update phoenix News Success");
		}
		else
			Logger.getLogger("").info("Update phoenix News fail");
	}
	
	public static Runnable getPhoenixNewsTask(){
    	Runnable task=new Runnable() {
			public void run() {
				PhoenixNewsUtil.updateLatestNews();
			}
		};
		return task;
    }
	
}
